package com.ifcar.app.activity;

import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.activity.newspage.NewsFragment;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.model.News;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.Constant;
import com.ifcar.app.util.GroupAdapter;
import com.ifcar.app.util.GroupListView;
import com.ifcar.app.util.NeteaseHttpClient;
import com.ifcar.app.util.PicUtil;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.util.BaseImageDownloader.FlushedInputStream;
import com.ifcar.app.util.GroupAdapter.ItemPosition;
import com.ifcar.app.util.GroupListView.TopViewCallback;
import com.ifcar.app.view.PullRefreshListView;
import com.ifcar.app.view.PullRefreshListView.OnRefreshListener;
import com.ifcar.app.activity.R;
import com.netease.util.Pair;

public class SpecialAritcleTwo extends BaseActivity implements OnGestureListener, OnItemClickListener, OnRefreshListener {
	private ListView specialarticle_list;
	private GroupListView grouplistview;
	private GroupAdapter<String, HashMap<String, Object>> adapter;
	private List<Pair<String, List<Map<String, Object>>>> grouplist;
	private TextView top_main_text;
	private ProgressBar top_progressbar;
	private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
	private RelativeLayout top_image_text;
	private ImageView top_image;
	private TextView top_text;
	private LinearLayout mProgressbarLoadingLayout;
	private Map<String, Object> first;
	private String specialID = "";
	private String headtitle = "专题";
	public static String TAG = "SpecialAritcle";
	private SharedPreferences sp;
	private LayoutInflater mInflater;
	private ThemeSettingsHelper themeSettingsHelper;
	private SharedPreferences set_prefs;
	private boolean isreflash = false;
	private RelativeLayout top_main_bottom;
	private UpdateReceiver updateReceiver;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.specialarticletwo);
		themeSettingsHelper = getThemeSettingsHelper();
		set_prefs = PreferenceManager.getDefaultSharedPreferences(this);
		gestureScanner = new GestureDetector(this);
		initData();
		findViews();
		setAdapter();
		setListeners();
		loaddata(false);
		setMenu();
        if(null==updateReceiver){
            updateReceiver = new UpdateReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(StringUtil.OFFLINEUPDATE);
            registerReceiver(updateReceiver, filter);
        }
	}
	
	@Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if(null!=adapter){
            adapter.notifyDataSetChanged();
        }
 }
	 
	   @Override
	    protected void onDestroy() {
	            // TODO Auto-generated method stub
	            super.onDestroy();
	            data.clear();
	            if(null!=grouplist) grouplist.clear();
	            
	            this.unregisterReceiver(updateReceiver);
	   }
	
	private void initData(){
		
		Bundle b = getIntent().getExtras();
		if(null!=b){
			specialID = b.getString(GetColumnsInfo.SPECIAL_ID_TAG);
			
			String ispush = b.getString("push");
			
			if(null!=ispush && "push".equals(ispush)){
			    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		        mNotificationManager.cancel(R.drawable.stat_download_icon);
			}
		}
		sp = getSharedPreferences(StringUtil.PREFERENCE_SPECIAL_BANNER, Context.MODE_PRIVATE);
		
	}
	
	@Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        menu_display = false;
    }
	
	private boolean menu_display = false;
	private LinearLayout menu_refresh;
	private LinearLayout menu_my_comment;
	private LinearLayout menu_setting;
	private LinearLayout menu_my_collect;
	private View menu_1;
    private View menu_2;
	private void setMenu() {
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.special_menu, null);
		menu_1 = layout.findViewById(R.id.menu_tabrow_1);
        menu_2 = layout.findViewById(R.id.menu_tabrow_2);
		menu_refresh = (LinearLayout)layout.findViewById(R.id.menu_refresh);
		menu_my_comment = (LinearLayout)layout.findViewById(R.id.menu_my_comment);
		menu_setting = (LinearLayout)layout.findViewById(R.id.menu_setting);
		menu_my_collect = (LinearLayout)layout.findViewById(R.id.menu_my_collect);
		
		menu_refresh.setOnClickListener(menuRefreshListener);
		menu_my_comment.setOnClickListener(menuMyCommentListener);
		menu_setting.setOnClickListener(menuSettingListener);
		menu_my_collect.setOnClickListener(menuMyCollectListener);
		
		
		menuWindow = new PopupWindow(layout,LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); //后两个参数是width和height
		menuWindow.setAnimationStyle(R.style.menuPopupAnimation);
		menu_display = false;
	}
	
	// 刷新
	private View.OnClickListener menuRefreshListener = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			
			menuWindow.dismiss();
			menu_display = false;
			grouplistview.refresh();
			
		}
	};
	// 我的跟贴
	private View.OnClickListener menuMyCommentListener = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent(SpecialAritcleTwo.this, MyCommentsActivity.class);			
			startActivity(intent);
			menuWindow.dismiss();
			menu_display = false;
		}
	};
	//我的收藏
    private View.OnClickListener menuMyCollectListener = new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Intent intent = new Intent(SpecialAritcleTwo.this, CollectActivity.class);           
            startActivity(intent);
            menuWindow.dismiss();
            menu_display = false;
        }
    };
	
	// 设置
	private View.OnClickListener menuSettingListener = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent(SpecialAritcleTwo.this, SettingsActivity.class);			
			startActivity(intent);
			menuWindow.dismiss();
			menu_display = false;
		}
	};
	
	public void goBackClick(View view){
		finish();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(event.getRepeatCount()>1){
			return super.onKeyDown(keyCode, event);
		}
		if(menu_display){
			menuWindow.dismiss();
			menu_display = false;
			return true;
		}
		if(keyCode == KeyEvent.KEYCODE_MENU){
			if(!menuWindow.isShowing()){
			    findViewById(R.id.specialarticle).post(new Runnable() {
                    public void run() {
                        menuWindow.showAtLocation(findViewById(R.id.specialarticle), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                        menu_display = true;
                    }
                });
			}else{
				//如果当前已经为显示状态，则隐藏起来
				menuWindow.dismiss();
				menu_display = false;
			}
			
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(menuWindow.isShowing()){ // 点击屏幕时，隐藏菜单
			menuWindow.dismiss();
			menu_display = false;
			return true;
		}
		
		gestureScanner.onTouchEvent(ev);
		boolean result = false;
		try {
			result = super.dispatchTouchEvent(ev);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	private void findViews(){
		grouplistview = (GroupListView)findViewById(R.id.specialarticle_list);
		specialarticle_list = grouplistview.getListView();
		top_main_bottom = (RelativeLayout) findViewById(R.id.top_main_top);
		top_main_text = (TextView)findViewById(R.id.top_main_text);
		top_progressbar = (ProgressBar)findViewById(R.id.top_progressbar);
		top_main_text.setText(headtitle);
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		top_image_text = (RelativeLayout) mInflater.inflate(R.layout.top_banner_image_text, null);
		top_image = (ImageView)top_image_text.getChildAt(0);
		top_image.setTag("top_image");
		top_text = (TextView)top_image_text.getChildAt(1);
		top_text.setVisibility(View.GONE);
		mProgressbarLoadingLayout = (LinearLayout) findViewById(R.id.loadingbar);
		
		grouplistview.setTopViewCallback(new TopViewCallback() {

            @Override
            public View createView() {
                // TODO Auto-generated method stub
                View convertView = mInflater.inflate(R.layout.specialarticletwo_tipstitle, null);
                return convertView;
            }

            @Override
            public void updateView(View view, int group) {
                // TODO Auto-generated method stub
                String groupstr = (String)adapter.getGroup(group);
                TextView category_title = (TextView)view.findViewById(R.id.category_title);
                category_title.setText(groupstr);
            }
            
            
        });
		preparePullRefreshView();
	}
	
	private void preparePullRefreshView() {
	    grouplistview.setRefreshView(R.layout.refreshing_view);
	    grouplistview.setOnRefreshListener("", this);
    }
    
    @Override
    public void updateRefreshView(String tag, View view, int lastState,  int state) {           
        TextView indicatorText = (TextView)view.findViewById(R.id.indicator_text);
        View indicatorArrow = view.findViewById(R.id.indicator_arraw);
        View refreshPb = view.findViewById(R.id.refreshing_pb);
        
        if (lastState == PullRefreshListView.REFRESH_STATE_IDLE) {
            TextView refreshTime = (TextView)view.findViewById(R.id.refresh_time);
            refreshTime.setText(StringUtil.getRefreshTimeStr(this, specialID));
        }
        
        switch (state) {
        case PullRefreshListView.REFRESH_STATE_IDLE:

            break;
        case PullRefreshListView.REFRESH_STATE_SHOWING:
            indicatorArrow.setVisibility(View.VISIBLE);
            refreshPb.setVisibility(View.INVISIBLE);
            indicatorArrow.setEnabled(true);
            if (lastState == PullRefreshListView.REFRESH_STATE_PREPARE_REFRESHING) {
                indicatorArrow.startAnimation(AnimationUtils.loadAnimation(SpecialAritcleTwo.this, R.anim.pull_indicator_arrow));
            }
            
            indicatorText.setText(R.string.pull_down_refresh);

            break;
        case PullRefreshListView.REFRESH_STATE_PREPARE_REFRESHING:
            indicatorArrow.setVisibility(View.VISIBLE);
            refreshPb.setVisibility(View.INVISIBLE);
            indicatorArrow.setEnabled(false);
            if (lastState == PullRefreshListView.REFRESH_STATE_SHOWING) {
                indicatorArrow.startAnimation(AnimationUtils.loadAnimation(SpecialAritcleTwo.this, R.anim.pull_indicator_arrow));
            }
            indicatorText.setText(R.string.relese_refresh);
            
            break;
        case PullRefreshListView.REFRESH_STATE_REFRESHING:
            indicatorArrow.setVisibility(View.INVISIBLE);
            refreshPb.setVisibility(View.VISIBLE);
            indicatorArrow.clearAnimation();
            indicatorText.setText(R.string.refreshing);
            break;
        default:
            break;
        }
    }
    
    @Override
    public boolean onPrepareRefresh(String tag) {
        
        return true;
    }
    
    @Override
    public void doRefresh(String tag) {
       top_progressbar.setVisibility(View.VISIBLE);
       loaddata(true);
    }
	
	private void setAdapter(){
		
	}
	
	private boolean isNeedRefresh(){
	    
	    boolean needRefresh = StringUtil.isNeedRefresh(this, specialID);
	    if(!needRefresh){
	        return needRefresh;
	    }else{
	        return StringUtil.isTipsAfterOfflineDownload(this);
	    }
	    
	}
	
    private class ViewHolder {
        public TextView title;
        public TextView article_date;
        public TextView comment_count;
        
    }
    
    private class ViewHolder1 {
        public TextView category_title;
        
    }

    
	private void setListeners(){
		specialarticle_list.setOnItemClickListener(this);
		
		top_main_bottom.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(null!=specialarticle_list){
                    specialarticle_list.setSelection(0);
                }
            }
		});
	}
	
	private void loaddata(boolean isreflash){
	   
	      if(!Tools.CheckNetwork(this)) {
	          if(isreflash || isNeedRefresh()){
	              Toast.makeText(this, "网络连接错误", Toast.LENGTH_SHORT).show();
	              mProgressbarLoadingLayout.setVisibility(View.GONE);
	              grouplistview.refreshDone();
	              top_progressbar.setVisibility(View.GONE);
	              return;
	          }
          } else {
              if(!isreflash)mProgressbarLoadingLayout.setVisibility(View.VISIBLE); 
          }
	   
		
		if (!isreflash) {
		    getData(data,specialID);
		}
		
		if(null!=data && data.size()>0){
		    
			if(Tools.CheckNetwork(this)) {
				top_progressbar.setVisibility(View.VISIBLE);
				new Thread(){
					public void run(){
						
						data.clear();
						data.addAll(GetColumnsInfo.getSpecialArticleList(GetColumnsInfo.SpcialArticle_Url, specialID, SpecialAritcleTwo.this));
						News.insertSpecialListToDB(db,data,specialID);
		                StringUtil.updateRefreshTime(SpecialAritcleTwo.this, specialID);
						handler.sendEmptyMessage(0);
					}
				}.start();
			}else{
			    handler.sendEmptyMessage(0);
			}
		}else{
			new Thread(){
				public void run(){
					
					data.clear();
					data.addAll(GetColumnsInfo.getSpecialArticleList(GetColumnsInfo.SpcialArticle_Url, specialID, SpecialAritcleTwo.this));
					News.insertSpecialListToDB(db,data,specialID);
	                StringUtil.updateRefreshTime(SpecialAritcleTwo.this, specialID);
					handler.sendEmptyMessage(0);
				}
			}.start();
		}
		
		
	}
	
	private void setHeaderPic(Map<String, Object> first, final ImageView top_image, String key) {
		String imgsrc = "";
		if(top_image == null) return;
		if(first.get(key) != null) {
			imgsrc = first.get(key).toString();
		}
		imgsrc = PicUtil.getHeandBitMapURL(imgsrc, this);
		boolean downpic = set_prefs.getBoolean("downpic", false);
		if(imgsrc != null && !imgsrc.equals("")) {
			if(PicUtil.isLocalPicExit(imgsrc.substring(imgsrc.lastIndexOf("/")+1, imgsrc.length()))) {
				WeakReference<Bitmap> bitmapReference = new WeakReference<Bitmap>(PicUtil.readTempJPEGFile( 
						imgsrc.substring(imgsrc.lastIndexOf("/")+1, imgsrc.length()), getResources().getDrawable(R.drawable.vote_default)));
				
				top_image.setImageBitmap(bitmapReference.get());
			} else {
				int w = 0;
				int h = 0;
				
				if(GetColumnsInfo.SPECIAL_BANNER.equals(key)){
					
					w = screenwidth;
                    h = Tools.getSpecialBannerCutHeadPicHeight(screenwidth);
				    
				}else{
					w = screenwidth;
					h = Tools.getCutHeadPicHeight(screenwidth);
					top_image.setImageDrawable(getResources().getDrawable(R.drawable.vote_default));
				}
				
				final String url = imgsrc;	
				final int bitmapW = w;
				final int bitmapH = h;
     			
				if(Tools.isshowimg(downpic, SpecialAritcleTwo.this)){
				    new Thread() {
                        public void run() {
                            Bitmap bm = null;
                      
                            
                                try {
                                    if (url == null || url.equals("")) {
                                        Message msg = Message.obtain();
                                        msg.obj = top_image;
                                        msg.what = 14;
                                        handler.sendMessage(msg);
                                       
                                    } else {
                                        
                                        HttpParams httpParams = new BasicHttpParams();
                                        //设置连接超时和数据读取超时
                                        HttpConnectionParams.setConnectionTimeout(httpParams, Constant.TIMEOUT);
                                        HttpConnectionParams.setSoTimeout(httpParams, Constant.TIMEOUT);
                                        DefaultHttpClient httpClient = NeteaseHttpClient.getHttpClient(httpParams);
                                        Tools.setHttpClientHostProxy(httpClient, SpecialAritcleTwo.this);
                                        HttpGet request = new HttpGet(PicUtil.getImgUrlByNetType(url,SpecialAritcleTwo.this));
                                        HttpResponse response = httpClient.execute(request);
                                        HttpEntity entity = response.getEntity();
                                        InputStream is = entity.getContent();
                                        
                                        if (is == null) {
                                            Message msg = Message.obtain();
                                            msg.obj = top_image;
                                            msg.what = 14;
                                            handler.sendMessage(msg);
                                        } else {
                                            try {
                                                bm = PicUtil.cutBitmap(BitmapFactory.decodeStream(new FlushedInputStream(is)), bitmapW, bitmapH,true);
                                            } catch (Exception e) {
                                             
                                            }catch (OutOfMemoryError error) {
                                               
                                            }
                                            if(null!=bm){
                                                PicUtil.saveMyBitmap(url.substring(url.lastIndexOf("/") + 1, url.length()), bm);
                                                Message msg = Message.obtain();
                                                msg.obj = top_image;
                                                msg.what = 15;
                                                Bundle bundle = new Bundle();
                                                bundle.putParcelable("headpic", bm);
                                                msg.setData(bundle);
                                                handler.sendMessage(msg);
                                            }else{
                                                Message msg = Message.obtain();
                                                msg.obj = top_image;
                                                msg.what = 14;
                                                handler.sendMessage(msg);
                                            }
                                            is.close();
                                            entity.consumeContent();
                                        }
                                       
                                    }
                                } catch (Exception e) {
                                    Message msg = Message.obtain();
                                    msg.obj = top_image;
                                    msg.what = 14;
                                     handler.sendMessage(msg);
                                }catch (OutOfMemoryError e) {
                                    Message msg = Message.obtain();
                                    msg.obj = top_image;
                                    msg.what = 14;
                                    handler.sendMessage(msg);
                                }
                            
                                
                            
                        }
                    }.start();
				}
				
			}
		}
	}
	
	private void getData( List<Map<String, Object>> data,String columnID){
		
		String sql = "select * from " + NewsSQLiteOpenHelper.NEWS_LIST_TABLE + 
		" where " + NewsSQLiteOpenHelper.NEWS_COL_ID + "='" + columnID + "'" +
		" order by "+NewsSQLiteOpenHelper.NEWS_SPECIAL_INDEX+" ASC ,"+
		NewsSQLiteOpenHelper.NEWS_AUTO_ID+" ASC ," +
		NewsSQLiteOpenHelper.NEWS_SPECIAL_TNAME+" DESC ";
		Cursor cursor = db.rawQuery(sql,null);
		if(cursor != null && cursor.getCount()!= 0) {
			data.clear();
			HashMap<String, Object> map = null;
			for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
				map = new HashMap<String, Object>();
    			map.put(GetColumnsInfo.DOCID_TAG, 
    					cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_DOC_ID)));
    			map.put(GetColumnsInfo.IMGSRC_TAG, 
    					cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_IMG_SRC)));
    			map.put(GetColumnsInfo.DIGEST_TAG, 
    					cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_DIGEST)));
    			map.put(GetColumnsInfo.REPLYCOUNT_TAG, 
    					cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_REPLY_COUNT)));
    			map.put(GetColumnsInfo.URL_TAG, 
    					cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_URL)));
    			map.put(GetColumnsInfo.TITLE_TAG, 
    					cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_TITLE)));
    			if(!cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_PTIME)).equals("")) {
        			map.put(GetColumnsInfo.PTIME_TAG, cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_PTIME)));
    			}
    			map.put(GetColumnsInfo.HASIMG_TAG, 
    					cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_IS_HASIMG)));
    			map.put(GetColumnsInfo.SPECIAL_TNAME_TAG, 
    					cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_SPECIAL_TNAME)));
    			map.put(GetColumnsInfo.SPECIAL_INDEX_TAG, cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.NEWS_SPECIAL_INDEX)));
    			
    			
    			data.add(map);
    			
			}
		}
		cursor.close();
		
	}
	
	
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			switch(msg.what) {
			    case 0:	
			    	
			        grouplistview.refreshDone();
			    	mProgressbarLoadingLayout.setVisibility(View.GONE);
			    	top_progressbar.setVisibility(View.GONE);
			    	
			    	if(null!=data && data.size()>0){
			    	
			    	   grouplist = Tools.toGropuList4Special(data);
                       first = data.get(0);
                       data.remove(0);

						String banner = sp.getString(specialID, "");
						if(null!=banner && !"".equals(banner)){
						    first.put(GetColumnsInfo.SPECIAL_BANNER, banner);
						    setHeaderPic(first, top_image, GetColumnsInfo.SPECIAL_BANNER);        
						}else{
						    setHeaderPic(first, top_image, GetColumnsInfo.IMGSRC_TAG);        
						}
						
						top_text.setText(first.get(GetColumnsInfo.TITLE_TAG).toString());

						specialarticle_list.removeHeaderView(top_image_text);
						specialarticle_list.addHeaderView(top_image_text, null, false);

						
						adapter = new GroupAdapter(grouplist) {

				            @Override
				            public View getChildView(int groupPosition, int childPosition, View convertView,
				                    ViewGroup parent) {
				                ViewHolder holder = null;
				                if (convertView == null) {
				                    convertView = mInflater.inflate(R.layout.specialarticletwo_list_item, null);
				                    holder = new ViewHolder();
				                    holder.title = (TextView)convertView.findViewById(R.id.title);
				                    holder.article_date = (TextView)convertView.findViewById(R.id.article_date);
				                    holder.comment_count = (TextView)convertView.findViewById(R.id.comment_count);
				                    convertView.setTag(holder);
				                }
				                
				              //添加样式
                                
				                
				                holder = (ViewHolder)convertView.getTag();
				                themeSettingsHelper.setTextViewColor(SpecialAritcleTwo.this, holder.title, R.color.list_title_color);
				                themeSettingsHelper.setTextViewColor(SpecialAritcleTwo.this, holder.article_date, R.color.list_desc_color);
				                themeSettingsHelper.setTextViewColor(SpecialAritcleTwo.this, holder.comment_count, R.color.list_desc_color);
				                HashMap<String, Object> child = (HashMap<String, Object>)getChild(groupPosition, childPosition);
				                
				                holder.title.setText((String)child.get(GetColumnsInfo.TITLE_TAG));
				                
				                String sql = "select * from "
                                    + NewsSQLiteOpenHelper.ARTICLE_READ_LIST_TABLE
                                    + " where "
                                    + NewsSQLiteOpenHelper.ARTICLE_READ_DOC_ID + "=?";
				                
				                Cursor cursor = db.rawQuery(sql,new String[] { child.get(
                                        GetColumnsInfo.DOCID_TAG).toString()});
				                if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()
                                && cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.ARTICLE_READ_STATUS)).equals("Y")){
				                    
				                    holder.title.setTextAppearance(SpecialAritcleTwo.this, R.style.list_title_readed_style);
				                    themeSettingsHelper.setTextViewColor(SpecialAritcleTwo.this, holder.title, R.color.list_title_readed_color);
				                    
				                }
				                cursor.close();
				                holder.article_date.setText((String)child.get(GetColumnsInfo.PTIME_TAG));
				                holder.comment_count.setText((String)child.get(GetColumnsInfo.REPLYCOUNT_TAG));
				                
				                
				                return convertView;
				            }

				            @Override
				            public View getGroupView(int groupPosition, View convertView, ViewGroup parent) {
				                ViewHolder1 holder1 = null;
				                if (convertView == null) {
				                    convertView = mInflater.inflate(R.layout.specialarticletwo_tipstitle, null);
				                    holder1 = new ViewHolder1();
				                    holder1.category_title = (TextView)convertView.findViewById(R.id.category_title);
				                    convertView.setTag(holder1);
				                }
				                holder1 = (ViewHolder1)convertView.getTag();
				                String group = (String) getGroup(groupPosition);
				                holder1.category_title.setText(""+group);
				                return convertView;
				            }
				            
				            
				        };
						
						adapter.notifyDataSetChanged();
						
						grouplistview.setAdapter(adapter);
			    		
			    	}
			    	
			    	
			    	break;
			    case 14:
					ImageView top_image = (ImageView)msg.obj;
					String banner = sp.getString(specialID, "");
					if("".equals(banner)){
					    top_image.setImageDrawable(getResources().getDrawable(R.drawable.vote_default));
					}
					break;
				case 15:
					ImageView top_image2 = (ImageView)msg.obj;
					Bundle bundle = msg.getData();
					top_image2.setImageBitmap((Bitmap)bundle.getParcelable("headpic"));
					break;
			}
		}
	};

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		// TODO Auto-generated method stub
		
	  
	    if(position==0 || adapter==null){
            return;
        }
	    position = position-specialarticle_list.getHeaderViewsCount();
	    ItemPosition iposition = adapter.getRealPosition(position);
	    
	    HashMap<String, Object> child = (HashMap<String, Object>)adapter.getChild(iposition.group, iposition.pos);
	    
	    if(null==child){
	        return;
	    }
	    position = position-iposition.group;

		String docid = "";
		String url = "";
		String imgsrc = "";
		String digest = "";
		String replyCount = "";
		String title = "";
		String ptime = "";
		
		Intent itemintent = new Intent(SpecialAritcleTwo.this, NewsPage.class);
		Bundle b = new Bundle();

		String idJsonString = StringUtil.createIdString(data);
        if(!TextUtils.isEmpty(idJsonString)){
        	b.putString(NewsFragment.ID_JSON_STRING, idJsonString);
        }
        
		b.putString(GetColumnsInfo.TNAME_TAG, "专题");
	
			docid = child.get(GetColumnsInfo.DOCID_TAG)==null?"":child.get(GetColumnsInfo.DOCID_TAG).toString();
			url = child.get(GetColumnsInfo.URL_TAG)==null?"":child.get(GetColumnsInfo.URL_TAG).toString();
			imgsrc = child.get(GetColumnsInfo.IMGSRC_TAG)==null?"":child.get(GetColumnsInfo.IMGSRC_TAG).toString();
			digest = child.get(GetColumnsInfo.DIGEST_TAG)==null?"":child.get(GetColumnsInfo.DIGEST_TAG).toString();
			replyCount = child.get(GetColumnsInfo.REPLYCOUNT_TAG)==null?"":child.get(GetColumnsInfo.REPLYCOUNT_TAG).toString();
			title = child.get(GetColumnsInfo.TITLE_TAG)==null?"":child.get(GetColumnsInfo.TITLE_TAG).toString();
			ptime = child.get(GetColumnsInfo.PTIME_TAG)==null?"":child.get(GetColumnsInfo.PTIME_TAG).toString();

		if(docid != null && !docid.equals("")) {
			b.putString(GetColumnsInfo.DOCID_TAG, docid);
			b.putString(GetColumnsInfo.URL_TAG, url);
			b.putString(GetColumnsInfo.IMGSRC_TAG, imgsrc);
			b.putString(GetColumnsInfo.DIGEST_TAG, digest);
			b.putString(GetColumnsInfo.REPLYCOUNT_TAG, replyCount);
			b.putString(GetColumnsInfo.TITLE_TAG, title);
			b.putString(GetColumnsInfo.PTIME_TAG, ptime);

			b.putString(GetColumnsInfo.TID_TAG, specialID);
			b.putString(HomePage.POSITION, ""+(position-1));
			b.putBoolean(GetColumnsInfo.HEADLINE_TAG, false);
			itemintent.putExtras(b);
			startActivity(itemintent);
		}else {
			Toast.makeText(SpecialAritcleTwo.this, "打开新闻正文失败", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	@Override
    public void onApplyTheme() {
        super.onApplyTheme();
        themeSettingsHelper.setTextViewColor(this, top_main_text, R.color.main_title_color);
        themeSettingsHelper.setImageViewSrc(this, R.id.top_id_image, R.drawable.netease_top);
        themeSettingsHelper.setViewBackgroud(this, R.id.top_main_top, R.drawable.top_background);
        themeSettingsHelper.setListViewDivider(this, specialarticle_list, R.drawable.list_divider_line);
        themeSettingsHelper.setViewBackgroudColor(this, R.id.specialarticle, R.color.main_bg_color);
        
        themeSettingsHelper.setViewBackgroudColor(this, menu_1, R.color.menu_layout_bg_color);
        themeSettingsHelper.setViewBackgroudColor(this, menu_2, R.color.menu_layout_bg_color);
        
        themeSettingsHelper.setViewBackgroud(this, menu_refresh, R.drawable.menu_background);
        themeSettingsHelper.setTextViewColor(this, (TextView)menu_refresh.getChildAt(1), R.color.menu_text_color);
        themeSettingsHelper.setViewBackgroud(this, menu_my_comment, R.drawable.menu_background);
        themeSettingsHelper.setTextViewColor(this, (TextView)menu_my_comment.getChildAt(1), R.color.menu_text_color);
        
        themeSettingsHelper.setViewBackgroud(this, menu_setting, R.drawable.menu_background_below);
        themeSettingsHelper.setTextViewColor(this, (TextView)menu_setting.getChildAt(1), R.color.menu_text_color);
        themeSettingsHelper.setViewBackgroud(this, menu_my_collect, R.drawable.menu_background_below);
        themeSettingsHelper.setTextViewColor(this, (TextView)menu_my_collect.getChildAt(1), R.color.menu_text_color);
      //返回夜间模式
        themeSettingsHelper.setImageViewSrc(this, R.id.go_back_common_btn, R.drawable.go_back);
       
        
	}
	private GestureDetector gestureScanner;
	
	@Override
    public boolean onTouchEvent(MotionEvent event) {
	   return gestureScanner.onTouchEvent(event);
	}

    @Override
    public boolean onDown(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }
    
    private class UpdateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(StringUtil.OFFLINEUPDATE.equals(action)){
                getData(data,specialID);
                handler.sendEmptyMessage(0);
            }
        }
    }

   
}
